# coding:utf-8

# """
# @Time : 2023/07/17 16:31
# @Auth : WangJingbo
# @File : app.py
# @Desc : 4级分类接口
# """
import time
import json
import traceback
from typing import Optional,Union
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
import uvicorn
from transformers import pipeline
from fastapi.middleware.cors import CORSMiddleware
import config
from logger import configure_logging

with open(config.label_path, "r", encoding="utf-8") as f:
    true_class = json.load(f)

pipe = pipeline(task="text-classification",model=config.model_path)


# app = FastAPI()
app = FastAPI(
	title='xxxx ',
	description='xxx',
	version='1.0.0'
)
app.add_middleware(
	CORSMiddleware,
	# 允许跨域的源列表，例如 ["http://www.example.org"] 等等，["*"] 表示允许任何源
	allow_origins=["*"],
	# 跨域请求是否支持 cookie，默认是 False，如果为 True，allow_origins 必须为具体的源，不可以是 ["*"]
	allow_credentials=False,
	# 允许跨域请求的 HTTP 方法列表，默认是 ["GET"]
	allow_methods=["*"],
	# 允许跨域请求的 HTTP 请求头列表，默认是 []，可以使用 ["*"] 表示允许所有的请求头
	# 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
	allow_headers=["*"],
	# 可以被浏览器访问的响应头, 默认是 []，一般很少指定
	# expose_headers=["*"]
	# 设定浏览器缓存 CORS 响应的最长时间，单位是秒。默认为 600，一般也很少指定
	# max_age=1000
)

logger = configure_logging()

#工单内容
class MatchInput(BaseModel):
    content: str
    
@app.post("/text_classification/")
async def infer(item: MatchInput):  # item需要与MatchInput对象定义保持一致
#     """
#     获取派单类别
#     """

    start_time = time.time()
    result = dict()
    try:
        
        # classId = item.classId
        text = item.content

        assert text, 'The `text` parameter cannot be empty.'
        logger.debug(text)
        
        pipe_res=pipe(text)
        
        res = pipe_res[0]['label']
        result['code'] = 200
        result['msg'] = 'success'
        result['class'] = true_class[res]
        

    except Exception as e:
        traceback.print_exc()
        result['code'] = 500
        result['msg'] = e.__str__()
        logger.error(e.__str__())
    result['cost'] = int((time.time() - start_time) * 1000)

    logger.info(result)

    return result


if __name__ == '__main__':
    # uvicorn.run(app='app:app', host="127.0.0.1", port=8000, reload=True, log_level='debug')
    uvicorn.run(app='app:app', host=config.host, port=config.port)

